#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time   :2021/12/17
# @Author :songtx
# @File   :io_status.py

import can
import time
import numpy as np
# from write_mariaDB import write_sql
# 问询can地址0x0201，返回4个2位16进制str，预存一组，差异检测，差异数据处理装入data_do(list)
# 问询can地址0x0301，返回4个2位16进制str，预存一组，差异检测，差异数据处理装入data_di(list)
# di状态增加上升沿/下降沿|edge(array)，短脉冲/长脉冲判断｜l_s_time(array)
# 未导入函数主程序


def io_status():
    global var1, var2, data_do, data_di  # 类型为list
    # global edge, l_s_time  # 长按和短按判断，类型为array元素为True/False
    inquiry_do = can.Message(arbitration_id=0x0201, data=[0x01], is_extended_id=False)  # 问询
    bus.send(inquiry_do)                    # 0x0201 DO状态 返回513
    message_do = bus.recv(timeout=1)        # 接收数据
    type_id_do = message_do.arbitration_id  # 返回can报文类型
    if type_id_do == 513:
        # time_float1 = message_do.timestamp          # 浮点数时间戳
        # time_date1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(message_do.timestamp)))  # 转str时间
        # 取回4个字节,预留32通道,bytearray->int->bin(str)->去'0b'->bin->左补32位->反向排列
        data_do = '{:0>32b}'.format(int(bin(int.from_bytes(message_do.data[0:4], "little")).replace('0b', ''), 2))[::-1]
        # print(data_do, type(data_do))
        if var1 != data_do:                 # 差异检测，差异写入数据库
            # write_sql(time_date1, type_id_do, data_do)+++++++++++注意排列顺序有修改
            var1 = data_do                  # 给中间值赋新值
        # else:
        #     time.sleep(0.1)                # 无差异，0.5s扫描一次DI状态

    inquiry_di = can.Message(arbitration_id=0x0301, data=[0x01], is_extended_id=False)
    bus.send(inquiry_di)                    # 0x0301  返回769/0x0301 di状态
    message_di = bus.recv(timeout=1)        # 接收数据
    type_id_di = message_di.arbitration_id  # 返回can报文类型
    if type_id_di == 769:
        # time_float2 = message_di.timestamp          # 浮点数时间戳
        # time_date2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(message_di.timestamp)))  # 转str时间
        # 取回4个字,预留32通道,bytearray->int->bin(str)->去'0b'->bin->左补32位->反向排列
        data_di = '{:0>32b}'.format(int(bin(int.from_bytes(message_di.data[0:4], "little")).replace('0b', ''), 2))[::-1]
        # print(data_di, type(data_di))
        if data_di != var2:                               # 差异检测，差异写入数据库
            # write_sql(time_date2, type_id_di, data_di)
            var2 = data_di  # 给中间值赋新值
        for j in range(32):
            if data_di[j] == '1':                     # 32点检测为1
                edge[0, j] += 1                       # 累加迭代，写入edge[0]
                if edge[0, j] == 3:                   # edge[0]=计数器
                    edge[1, j] = 1                    # edge[1]=短命令
                    edge[2, j] = 0                    # edge[2]=长命令
                if edge[0, j] == 10:
                    edge[1, j] = 0
                    edge[2, j] = 1
            else:                                     # 32点检测为0
                if edge[0, j] > 0:
                    edge[0, j] -= 1                   # 累减迭代，写入edge[0]

        print('接通计数', edge[0])
        print('短命令', edge[1])
        print('长命令', edge[2])


print('io_status初始化...')
bus = can.Bus(interface='socketcan', channel='can0', receive_own_messages=eval('False'))
var1 = '00000000000000000000000000000000'          # 参与差异判断和上升下降沿的中间变量
var2 = '00000000000000000000000000000000'          # 参与差异判断和上升下降沿的中间变量
data_do, data_di = 0, 0                            # 传回的DI/DO状态
edge = np.zeros(96, np.int8).reshape(3, 32)        # DI上升/下降沿检测,edge[0,0]第1个up，edge[1,0]第1个down
for i in range(60):
    io_status()
    time.sleep(1)
    # print('上升沿', edge[0])
    # print('下降沿', edge[1])
    # print('短脉冲', l_s_time[0])
    # print('长脉冲', l_s_time[1])
